<?php
/**
 * ebiz front
 *
 * Base Dao
 *
 * @author allen
 *
 */


class BaseDao
{
    protected $dbUtil;

    protected $_name;

    public function __construct(&$dbUtil){
        $this->dbUtil = $dbUtil;
    }

    public function update($data,$where=1){
    	$sql = '';//$sql = "update $this->_name set ";
    	$dataValues = array();
    	foreach($data as $key => $value){
    		$sql .= ", {$key} = ? ";//$sql .= " $key = ? ,";
    		$dataValues[] = $value;
    	}
    	$sql = substr($sql, 1);//$sql = substr($sql, 0, strlen($sql)-1);
    	$sql = "update {$this->_name} set {$sql} where {$where}";//$sql .= " where $where ";
    	return $this->dbUtil->ExecuteQuery( $sql, $dataValues );
    }

    public function insert($data){
        $keys = array_keys($data);
        $column = implode(",",$keys);
        $values = array();
        $dataValues = array();
        foreach($keys as $key){
        	$values[] = "?";
        	$dataValues[] = $data[$key];
        }
        $value = implode(",",$values);
        $sql = "insert into $this->_name ($column) values ($value)";
    	return $this->dbUtil->ExecuteQuery( $sql, $dataValues );
    }

    /**
     * Get last found rows, if the last select include 'SQL_CALC_FOUND_ROWS' option
     *
     * @example SELECT SQL_CALC_FOUND_ROWS * FROM `table` LIMIT 0,1
     * @return int
     */
    public function getLastFoundRows(){
        $arr_result = $this->dbUtil->SelectData('SELECT FOUND_ROWS() AS `ROWS`' , array());
        return $arr_result[0]['ROWS'];
    }

    /**
     * 获得指定数据表中的所有字段名
     *
     * @param string $str_tableName
     * @param boolean $bool_getFullName if true, the column name like `column` else column only
     * @return array|false if table not exists return false
     */
    public function getColumnsFromTable($str_tableName, $bool_getFullName = false){
        $str_sql = "SHOW CREATE TABLE $str_tableName";
        $arr_results = $this->dbUtil->SelectData($str_sql,array());
        if (empty($arr_results[0]))
            return false;
        preg_match_all( '/`([\w\d]+)`/i', $arr_results[0]['Create Table'], $arr_columns);
        if ($bool_getFullName)
            $arr_results = $arr_columns[0];
        else
            $arr_results = $arr_columns[1];
        array_shift($arr_results);//index 0 is table name
        return $arr_results;
    }

}


